package com.demo.controller;

import com.demo.entity.User;
import com.demo.model.base.RestResponse;
import com.demo.model.rest.UserRest;
import com.demo.service.UserService;
import com.demo.tool.JsonTool;
import com.demo.tool.StringTool;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Author:  Hardy
 * Date:    2018/7/18 20:05
 * Description:
 **/
@RestController
public class TestController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private UserService userService;

    // 测试查询和动态数据源
    @ApiOperation("测试查询和动态数据源")
    @RequestMapping(value = "/test/{userId}", method = RequestMethod.GET)
    public RestResponse test(@PathVariable("userId") long userId) {
        User user1 = userService.getUserM(1);
        User user2 = userService.getUserS(1);
        return new RestResponse<>().data(
                StringTool.formatStr(
                        "{}\n{}",
                        JsonTool.toJson(user1),
                        JsonTool.toJson(user2)
                ));
    }

    // 测试事务回滚
    @ApiOperation("测试事务")
    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public RestResponse test1(@RequestParam(defaultValue = "1") int age) {
        long id = userService.saveUser("小红", age);
        return new RestResponse<>().data(id);
    }

    // 测试更新
    @ApiOperation("测试更新")
    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public RestResponse test2(@RequestParam(defaultValue = "1") int id,
                              @RequestParam(defaultValue = "1") int age) {
        userService.updateUser(id, "小红", age);
        return new RestResponse();
    }

    // 测试 @Valid、BaseException
    @ApiOperation("测试@Valid")
    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    public RestResponse test3(@RequestBody @Valid UserRest rest) {
        return new RestResponse<>().data(rest);
    }
}
